using System;
using System.Collections;
using System.Collections.Generic;
using BCW.GameTypes.SkyBlock;
using ExitGames.Client.Photon;
using Holoville.HOTween;
using I2.Loc;
using Photon;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PVPManager : Photon.MonoBehaviour, IPunObservable
{
	public static PVPManager instance;

	public static float standartTimeRound = 240f;

	public static bool shouldCancelEndTdm;

	public static float timeRound = 240f;

	public static float kickDelay = 60f;

	[HideInInspector]
	public UILabel lbTimePVP;

	[HideInInspector]
	public UILabel lbKillPVP;

	[HideInInspector]
	public UILabel labelWinCash;

	[HideInInspector]
	public GameObject messageWait;

	[HideInInspector]
	public GameObject panelWin;

	[HideInInspector]
	public GameObject panelNoWin;

	public bool timerStart;

	public bool gameIsStarted;

	public bool endOfRound;

	public bool isFirstEnter = true;

	public int myRespect;

	public int addReputation;

	public int maxReputationFromThisMap;

	private Dictionary<string, ReputationMapInfo> info;

	private ReputationMapInfo infoFromThisMap;

	public Color colorTimerEnd = Color.red;

	private bool isTimerRed;

	[HideInInspector]
	public bool needToChangeRoundIndex;

	[HideInInspector]
	public double startTimePhoton = -1.0;

	private int _currentRound;

	private int countPlayerForStart = 2;

	public bool modeSandbox;

	private bool isDraw;

	public bool gameEnded;

	private Vector3 scaleTimer = new Vector3(1.5f, 1.5f, 1.5f);

	public IEnumerator updateTimer;

	public int countPlayersInMyTeam;

	public int myPlace;

	public static IEnumerator kickInactive;

	public int myPlayerPlace = -1;

	private bool firstCall = true;

	public bool needToCheckRoundIndexAfterPause;

	public double startRoundTimeOnPause;

	public int roundIndex;

	public int CurrentRound
	{
		get
		{
			return _currentRound;
		}
		set
		{
			if (PhotonNetwork.isMasterClient)
			{
				base.photonView.RPC("UpdateRondCount", PhotonTargets.All, value);
			}
		}
	}

	public int CountPlayerForStart
	{
		get
		{
			return countPlayerForStart;
		}
	}

	public static event Action onPVPStarted;

	private void Awake()
	{
		instance = this;
		TypeGame curTypeGame = GameController.instance.curTypeGame;
		if (curTypeGame == TypeGame.Pixelmon)
		{
			timeRound = PixelmonController.timeRound;
		}
		else
		{
			timeRound = standartTimeRound;
		}
		double time = PhotonNetwork.time;
		if (settings.offlineMode)
		{
			base.enabled = false;
		}
	}

	private void Start()
	{
		lbKillPVP = GameTopWindow.instance.lbKillPVP;
		if (GameController.instance.curTypeGame == TypeGame.TitanfallV2)
		{
			lbTimePVP = GameInfoWindow.instance.titanfalUI.timer;
			lbKillPVP = GameInfoWindow.instance.titanfalUI.kills;
		}
		else if (GameController.instance.curTypeGame == TypeGame.CopsAndRobbers)
		{
			GameTopWindow.instance.timerObjectCopsAndRobert.SetActive(true);
			GameTopWindow.instance.pvpTime.SetActive(false);
			lbTimePVP = GameTopWindow.instance.timerCopsAndRobert;
		}
		else
		{
			GameTopWindow.instance.timerObjectCopsAndRobert.SetActive(false);
			GameTopWindow.instance.pvpTime.SetActive(false);
			lbTimePVP = GameInfoWindow.instance.tdmInfoUI.lbTimer;
		}
		messageWait = GameTopWindow.instance.messageWait;
		Init();
		if (GameController.instance.curTypeGame == TypeGame.Zombe)
		{
			countPlayerForStart = settings.GetSettings(TypeGame.Zombe).minPlayerToStart;
		}
		else if (GameController.instance.curTypeGame == TypeGame.CopsAndRobbers)
		{
			countPlayerForStart = settings.GetSettings(TypeGame.CopsAndRobbers).minPlayerToStart;
		}
		if (GameController.instance.curTypeGame == TypeGame.RocketLeague)
		{
			countPlayerForStart = 2;
		}
	}

	private void OnDestroy()
	{
		if (GameplayEventsManager.instance != null)
		{
			GameplayEventsManager.instance.SaveAndReset(true);
			if (GameController.instance != null && GameController.instance.playerScript != null)
			{
				GameplayEventsManager.instance.SaveCounter(GameController.instance.playerScript.Points, settings.keySandboxKills);
			}
		}
		instance = null;
	}

	public void Init()
	{
		HOTween.Init();
		if (PhotonNetwork.room.customProperties.ContainsKey("timerStarted") && PhotonNetwork.room.customProperties["timerStarted"] != null)
		{
			timerStart = (bool)PhotonNetwork.room.customProperties["timerStarted"];
		}
		else
		{
			timerStart = false;
		}
		gameIsStarted = false;
		endOfRound = false;
		isFirstEnter = true;
		GameTopWindow.instance.IamWinnerActive = false;
		if (settings.offlineMode)
		{
			messageWait.SetActive(false);
		}
		else
		{
			lbKillPVP.text = string.Empty + 0;
			lbTimePVP.text = ConvertTimeToString((int)timeRound);
			if (PhotonNetwork.isMasterClient)
			{
				MapMetrix("Rooms amount");
			}
		}
		if (GameController.instance.curTypeGame == TypeGame.normal)
		{
			modeSandbox = true;
		}
		if (messageWait != null && !timerStart)
		{
			messageWait.SetActive(true);
		}
		if (TDMController.isTeamGameType || GameController.instance.curTypeGame == TypeGame.TitanfallV2)
		{
			if (updateTimer != null)
			{
				StopCoroutine(updateTimer);
			}
			updateTimer = UpdateTimer();
			StartCoroutine(updateTimer);
		}
	}

	public void TryStartTimer()
	{
		if (PhotonNetwork.room == null || timerStart || gameIsStarted || !CanStart() || !(GetTime() >= (double)timeRound))
		{
			return;
		}
		if (PhotonNetwork.time != 0.0)
		{
			ExitGames.Client.Photon.Hashtable customProperties = PhotonNetwork.room.customProperties;
			if (customProperties.ContainsKey("StartRoundTime"))
			{
				customProperties["StartRoundTime"] = PhotonNetwork.time;
			}
			else
			{
				customProperties.Add("StartRoundTime", PhotonNetwork.time);
			}
			PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { { "timerStarted", true } });
			timerStart = true;
			PhotonNetwork.room.SetCustomProperties(customProperties);
		}
		TDMController.instance.RestartTDM();
	}

	public static void SetCancelEndTdm(float cancelStateTimeOfLife)
	{
		CoroutineRunner.Instance.StartCoroutine(SetCancelEndTdmCoroutine(cancelStateTimeOfLife));
	}

	private static IEnumerator SetCancelEndTdmCoroutine(float cancelStateTimeOfLife)
	{
		shouldCancelEndTdm = true;
		yield return new WaitForSeconds(cancelStateTimeOfLife);
		shouldCancelEndTdm = false;
	}

	public void CheckState()
	{
		if (controllerConnectGame.reconnectRoom)
		{
			gameIsStarted = false;
		}
		else
		{
			if (PhotonNetwork.room == null || !(PhotonNetwork.time > 0.0) || !PhotonNetwork.room.customProperties.ContainsKey("StartRoundTime") || PhotonNetwork.room.customProperties["StartRoundTime"] == null)
			{
				return;
			}
			if (gameIsStarted && GetTime() >= (double)timeRound)
			{
				Debug.LogError("CheckState");
				ExitGames.Client.Photon.Hashtable customProperties = PhotonNetwork.room.customProperties;
				TimeOut();
			}
			else if (CanStart())
			{
				if (kickInactive != null)
				{
					StopCoroutine(kickInactive);
				}
				kickInactive = KickInactive(kickDelay);
				StartCoroutine(kickInactive);
				if (GameController.instance != null && GameController.instance.curTypeGame == TypeGame.Zombe)
				{
					TDMController.instance.zombieStart = 2;
				}
				gameIsStarted = true;
				endOfRound = false;
				if (PVPManager.onPVPStarted != null)
				{
					PVPManager.onPVPStarted();
				}
			}
		}
	}

	public double GetTime()
	{
		if (PhotonNetwork.room != null && PhotonNetwork.time > 0.0)
		{
			return Mathf.Abs((float)(PhotonNetwork.time - Convert.ToDouble(PhotonNetwork.room.customProperties["StartRoundTime"])));
		}
		return timeRound;
	}

	public bool CanStart()
	{
		if (gameIsStarted)
		{
			return false;
		}
		return GameController.instance.CurrentGameMode.CanStartNow();
	}

	public void ResetTimer()
	{
		timerStart = false;
		gameIsStarted = false;
		EndAnimPVPTime();
		lbTimePVP.text = ConvertTimeToString((int)timeRound);
		messageWait.SetActive(GameController.instance != null && GameController.instance.listPlayers.Count < countPlayerForStart);
	}

	[PunRPC]
	public void TimeOut()
	{
		BCWDebug.LogError("TimeOut");
		if (PhotonNetwork.isMasterClient)
		{
			MapMetrix("Match amount");
			PhotonNetwork.room.visible = false;
		}
		HitMarks.instance.ResetMark();
		if (modeSandbox)
		{
			EndSandbox();
			return;
		}
		PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { { "timerStarted", false } });
		timerStart = false;
		gameIsStarted = false;
		endOfRound = true;
		myPlayerPlace = GameController.instance.sortListPlayers();
		rednessScreen.inst.ResetMark();
		if (!shouldCancelEndTdm)
		{
			TDMController.instance.SetStartPVP(false);
		}
		if (BCWFlagManager.instance != null)
		{
			BCWFlagManager.instance.UpdateIgnoredRound();
		}
		GameInfoWindow.instance.ShowEndGameWindow();
		if (TDMController.isTeamGameType)
		{
			countPlayersInMyTeam = TDMController.instance.CountTeam(TDMController.myTeam);
			if (BCWFlagManager.instance != null)
			{
				BCWFlagManager.instance.ClearPlayers();
			}
		}
		if (GameController.instance.curTypeGame == TypeGame.RocketLeague)
		{
			RocketLeagueCotroller.instance.inRestartWindow = true;
		}
		if (GameController.instance.curTypeGame == TypeGame.TDM && GameplayEventsManager.instance != null)
		{
			GameplayEventsManager.instance.SaveCounter(GameController.instance.playerScript.Points, settings.keyPVPKills);
		}
		if (GameController.instance.curTypeGame == TypeGame.CopsAndRobbers && CopsAndRobbersController.instance != null)
		{
			CopsAndRobbersController.instance.EndGame();
		}
		gameEnded = true;
		EndTDMwithDelay();
	}

	private IEnumerator UpdateTimer()
	{
		while (true)
		{
			yield return new WaitForSeconds(1f);
			TryStartTimer();
			yield return null;
			CheckState();
			yield return null;
			UpdateIndictors();
		}
	}

	public void UpdateIndictors()
	{
		double num = (double)timeRound - GetTime();
		if (PhotonNetwork.isMasterClient && GameController.instance.curTypeGame != TypeGame.race && gameIsStarted)
		{
			if (GameController.instance.curTypeGame == TypeGame.CopsAndRobbers)
			{
				PhotonNetwork.room.visible = num > 120.0;
			}
			else if (GameController.instance.curTypeGame == TypeGame.Zombe)
			{
				PhotonNetwork.room.visible = num > 120.0;
			}
			else
			{
				PhotonNetwork.room.visible = num > 120.0;
			}
		}
		BCWDebug.Log("gameIsStarted " + gameIsStarted + "\n timerStart \n Time " + GetTime() + "\n startPVP player count " + GameController.instance.listPlayers.FindAll((PlayerBehavior x) => x.startPVP).Count, "PvPTimer");
		if (!settings.offlineMode && PhotonNetwork.room != null && PhotonNetwork.room.customProperties.ContainsKey("StartRoundTime") && PhotonNetwork.room.customProperties["StartRoundTime"] != null)
		{
			if (timerStart)
			{
				if (!gameIsStarted)
				{
					timerStart = false;
					ResetTimer();
				}
				else if (!controllerConnectGame.reconnectRoom)
				{
					if (num <= 5.0)
					{
						StartAnimPVPTime();
					}
					else if (isTimerRed && num > 6.0)
					{
						EndAnimPVPTime();
					}
					lbTimePVP.text = ConvertTimeToString(num);
				}
			}
			else if (gameIsStarted)
			{
				messageWait.SetActive(false);
				if (!timerStart)
				{
					PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { { "timerStarted", true } });
					timerStart = true;
				}
			}
			else
			{
				ResetTimer();
			}
		}
		if (GameController.instance.playerScript != null && !settings.offlineMode)
		{
			lbKillPVP.text = string.Empty + GameController.instance.playerScript.Points;
		}
	}

	public IEnumerator KickInactive(float delay)
	{
		if (GameController.instance.curTypeGame == TypeGame.TDM || GameController.instance.curTypeGame == TypeGame.tanks || GameController.instance.curTypeGame == TypeGame.RocketLeague || GameController.instance.curTypeGame == TypeGame.CopsAndRobbers || GameController.instance.curTypeGame == TypeGame.SkyBlock || GameController.instance.curTypeGame == TypeGame.Pixelmon || GameController.instance.curTypeGame == TypeGame.WalkingRobots || GameController.instance.curTypeGame == TypeGame.TitanfallV2)
		{
			yield return new WaitForSeconds(delay);
			bool photonStartPvp = PhotonNetwork.player.GetValueByKey(PlayerPropsKeys.startPVP, true);
			if (!GameController.instance.playerScript.startPVP && !photonStartPvp && gameIsStarted)
			{
				BCWDebug.LogError(string.Format("LOG: YOU WAS KICKED BECAUSE TIMER IS STARTED AND 'startPVP' EQUALS {0}. TELL PROGRAMMER ABOUT THIS.", GameController.instance.playerScript.startPVP));
				GameController.instance.exitToMenu();
			}
		}
	}

	private void StartAnimPVPTime()
	{
		isTimerRed = true;
		HOTween.Kill(lbTimePVP);
		lbTimePVP.color = colorTimerEnd;
		HOTween.To(lbTimePVP.transform, 0.5f, new TweenParms().Prop("localScale", scaleTimer).Ease(EaseType.Linear));
		HOTween.To(lbTimePVP.transform, 0.5f, new TweenParms().Prop("localScale", Vector3.one).Ease(EaseType.Linear).Delay(0.5f));
	}

	private void EndAnimPVPTime()
	{
		isTimerRed = false;
		HOTween.Kill(lbTimePVP);
		lbTimePVP.color = Color.white;
		lbTimePVP.transform.localScale = Vector3.one;
	}

	[PunRPC]
	public void UpdateRondCount(int round)
	{
		if (BCWDebug.isDebugBuild)
		{
			BCWDebug.Log("UpdateRondCount =" + round);
		}
		_currentRound = round;
	}

	public void ResetRoundCount()
	{
		if (BCWDebug.isDebugBuild)
		{
			BCWDebug.Log("ResetRoundCount");
		}
		_currentRound = 0;
	}

	private void MapMetrix(string paramName)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		dictionary.Add(paramName, SceneManager.GetActiveScene().name);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_PVP_MAP_METRIX, dictionary);
	}

	public string ConvertTimeToString(double curTime)
	{
		int num = (int)curTime / 60;
		int num2 = (int)curTime % 60;
		string text = num.ToString();
		string text2 = num2.ToString("D2");
		return text + ":" + text2;
	}

	public void Disconect()
	{
		gameIsStarted = false;
	}

	public void EndTDMwithDelay()
	{
		if (GameController.instance.curTypeGame == TypeGame.normal || GameController.instance.curTypeGame == TypeGame.OnlineSandbox || GameController.instance.curTypeGame == TypeGame.Offline)
		{
			Invoke("EndTDM", 4.5f);
		}
		else
		{
			Invoke("EndTDM", 5.5f);
		}
	}

	public void EndTDM()
	{
		if (!GameInfoWindow.instance.holder.activeInHierarchy)
		{
			GameInfoWindow.instance.ShowEndGameWindow();
		}
		needToChangeRoundIndex = true;
		if (GameplayNotificationController.instance != null)
		{
			GameplayNotificationController.instance.ClearBufer();
		}
		if (GameController.instance.curScriptLestnica != null)
		{
			GameController.instance.curScriptLestnica.OnStair(false);
		}
		GameController.instance.listPlayers.ForEach(delegate(PlayerBehavior x)
		{
			if (!x.isMine)
			{
				x.iconMiniMap.enabled = false;
			}
			if (x != PlayerBehavior.MyPlayer)
			{
				x.SetVisiblePlayerBesidesControl(false);
			}
		});
		if ((bool)WalkWindow.instance)
		{
			GameTopWindow.instance.isDeath = false;
		}
		if (PlayerBehavior.MyPlayer != null)
		{
			PlayerBehavior.MyPlayer.DeactivateAllChargesOnline();
		}
		WindowManager.instance.ShowWindow(typeof(GameTopWindow), true);
		PointerController.instance.RemoveAllPointers();
		HitMarks.instance.ResetMark();
		rednessScreen.inst.HideRedness();
		HitMarks.instance.gameObject.SetActive(false);
		rednessScreen.inst.gameObject.SetActive(false);
		if (TDMController.instance != null)
		{
			TDMController.instance.incrementTeams++;
			if (GameController.instance != null && GameController.instance.curTypeGame != TypeGame.Zombe)
			{
				TDMController.instance.ClearTeams();
			}
		}
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.carWeAreInId, -1);
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.isInCar, false);
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.privateCarPosition, Vector3.up * -1000f);
		if (GameController.instance.IsFlagGameType())
		{
			foreach (BCWFlag item in BCWFlagController.instance.GetListFlag())
			{
				item.AddPointOnFlag(string.Empty);
			}
			if (PhotonNetwork.isMasterClient)
			{
				BCWFlagController.instance.Reset();
			}
		}
		GameController.instance.CurrentGameMode.EndRound();
		gameEnded = false;
		if (shouldCancelEndTdm)
		{
			return;
		}
		GameController.instance.listPlayers.ForEach(delegate(PlayerBehavior x)
		{
			if (!x.isMine)
			{
				x.startPVP = false;
				x.CancelInvoke("reset");
				x.CancelInvoke("resetLocal");
				x.mecanimWrapper.Respawn();
			}
		});
		if (GameController.instance.playerScript != null)
		{
			if (GameController.instance.playerScript.inCar || GameController.instance.playerScript.inHelic)
			{
				GameController.instance.playerScript.isNeedGetOut = true;
				GameController.instance.playerScript.GetOutOfCar(false);
			}
			GameController.instance.playerScript.DisableJetpackParticle();
			GameController.instance.playerScript.tController.jetpack.activated = false;
			BCWDebug.LogError("END TDM!!");
			GameController.instance.playerScript.transform.position = Vector3.up * 1000f;
			GameController.instance.playerScript.CancelRespawn();
			GameController.instance.playerScript.tController.jetpack.fuel = 0f;
			GameController.instance.playerScript.tController.jetpack.Deactivate(true);
			GameController.instance.playerScript.SetActiveComponentBesidesControl(false);
			GameController.instance.playerScript.SetVisiblePlayerBesidesControl(false);
		}
		if (PrivateCarManager.instance != null && PrivateCarManager.instance.currentCar != null)
		{
			BCWDebug.Log("EndTDM");
			if (GameController.instance.curTypeGame == TypeGame.tanks || GameController.instance.curTypeGame == TypeGame.WalkingRobots)
			{
				PrivateCarManager.instance.currentCar.transform.position = Vector3.up * 1000f;
				PrivateCarManager.instance.currentCar.Disable();
			}
			else
			{
				PrivateCarManager.instance.currentCar.transform.position = Vector3.up * -1000f;
				PrivateCarManager.instance.ResetCarButton();
			}
		}
		SendTDMStatistics();
		ResetTimer();
		TypeGame typeGame = (GameController.instance.CurrentGameMode as DefaultGameMode).GameType;
		settings.IncreaseRoundCountForGameMode(typeGame, 1);
		StarterPacksManager.instance.RoundCountEvents(typeGame, settings.GetRoundCountForGameMode(typeGame));
		if (TDMController.isTeamGameType)
		{
			StarterPacksManager.instance.LoseCountEvent(TDMController.MyTeamResult());
		}
		if (PhotonNetwork.isMasterClient)
		{
			roundIndex++;
			PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
			{
				controllerConnectPhoton._indexRound,
				roundIndex
			} });
			needToChangeRoundIndex = false;
		}
		Invoke("ResetAllCar", 1f);
	}

	private void SendTDMStatistics()
	{
		FlurryWrapper.UpdateKillRate((float)GameController.instance.playerScript.Points / (float)GameController.instance.playerScript.DeathCount);
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (GameController.instance.curTypeGame == TypeGame.tanks)
		{
			dictionary.Clear();
			dictionary.Add((CupsManager.CurrentLeagueIndex + 1).ToString(), FlurryWrapper.TankKillRate((float)GameController.instance.playerScript.Points / (float)GameController.instance.playerScript.DeathCount));
			FlurryWrapper.LogEvent(FlurryWrapper.EV_TANKS_MODE_KILLRATE, dictionary);
		}
		if (PhotonNetwork.isMasterClient)
		{
			if (BCWFlagManager.instance != null && (GameController.instance.curTypeGame == TypeGame.tanks || GameController.instance.curTypeGame == TypeGame.TDM))
			{
				dictionary.Clear();
				dictionary.Add(GameController.instance.curTypeGame.ToString(), (BCWFlagManager.instance.winerTeam != 0) ? "Flag" : "Score");
				FlurryWrapper.LogEvent(FlurryWrapper.EV_TDM_VICTORY_CONDITION, dictionary);
			}
			if (GameController.instance.curTypeGame == TypeGame.CopsAndRobbers)
			{
				dictionary.Clear();
				dictionary.Add("Gates_destroy", CopsAndRobbersController.instance.gatesDestroyed.ToString());
				FlurryWrapper.LogEvent(FlurryWrapper.EV_COPS_AND_ROBBERS_STATS, dictionary);
			}
			if (BCWFlagManager.instance != null && GameController.instance.curTypeGame == TypeGame.SkyBlock)
			{
				dictionary.Clear();
				dictionary.Add("Special_block_grab", SkyBlockStatistics.blocksPickedUp.ToString());
				dictionary.Add("Special_block_drop", SkyBlockStatistics.blocksStacked.ToString());
				dictionary.Add("Victory_condition", (BCWFlagManager.instance.winerTeam != 0) ? "Holy_block" : "Score");
				FlurryWrapper.LogEvent(FlurryWrapper.EV_SKYBLOCKS_STATS, dictionary);
			}
			if (PixelmonController.instance != null && GameController.instance != null && GameController.instance.curTypeGame == TypeGame.Pixelmon)
			{
				dictionary.Clear();
				dictionary.Add("Victory_condition", (PixelmonController.instance.winnerTeam != TDMResult.None) ? "Pixelmon" : "Score");
				FlurryWrapper.LogEvent(FlurryWrapper.EV_PIXELMON_VICTORY, dictionary);
			}
			if (GameController.instance.curTypeGame == TypeGame.RocketLeague && !PhotonNetwork.room.customProperties.ContainsKey(PunTeams.Team.blue.ToString()))
			{
				int num = (int)PhotonNetwork.room.customProperties[PunTeams.Team.blue.ToString()];
				int num2 = (int)PhotonNetwork.room.customProperties[PunTeams.Team.red.ToString()];
				dictionary.Clear();
				dictionary.Add("Goals_count", (num + num2).ToString());
				FlurryWrapper.LogEvent(FlurryWrapper.EV_SKYBLOCKS_STATS, dictionary);
			}
			if (BCWFlagController.instance != null && GameController.instance.curTypeGame == TypeGame.WalkingRobots)
			{
				dictionary.Clear();
				dictionary.Add("Victory_condition", (BCWFlagController.instance.winnerTeam != TDMResult.None) ? "Flag" : "Score");
				FlurryWrapper.LogEvent(FlurryWrapper.EV_TITANFALL_STATS, dictionary);
			}
		}
	}

	private void ResetAllCar()
	{
		if (GameController.instance.curTypeGame != TypeGame.tanks && GameController.instance.curTypeGame != TypeGame.WalkingRobots)
		{
			GameController.instance.ResetAllCar();
		}
	}

	public void EndSandbox()
	{
		GameplayEventsManager.instance.SaveCounter(GameController.instance.playerScript.Points, settings.keySandboxKills);
		PointerController.instance.RemoveAllPointers();
		int countWinCash = GetCountWinCash();
		GameController.instance.playerScript.Points = 0;
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (GameController.instance.playerScript.DeathCount == 0)
		{
			GameController.instance.playerScript.DeathCount = 1;
		}
		FlurryWrapper.UpdateKillRate((float)GameController.instance.playerScript.Points / (float)GameController.instance.playerScript.DeathCount);
		GameController.instance.playerScript.DeathCount = 0;
		dictionary.Clear();
		string text = ((!string.IsNullOrEmpty(PhotonNetwork.room.customProperties["pass"].ToString())) ? "private" : string.Empty);
		dictionary.Add("Tier " + CupsManager.CurrentTier, "Sandbox " + text);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_MULTIPLAYER_MODE_RATING, dictionary);
		dictionary.Clear();
		dictionary.Add("Round", "Offline_sandbox");
		FlurryWrapper.LogEvent(FlurryWrapper.EV_ROUNDS_COUNT_BY_MODES, dictionary);
		if (countWinCash != 0)
		{
			GameTopWindow.instance.IamWinnerActive = true;
			if (!GameController.instance.playerScript.IamWinner)
			{
				GameController.instance.playerScript.photonView.RPC("SetWinnerIcon", PhotonTargets.All, true);
			}
			if (isDraw)
			{
				MessageManager.instance.CreateMessage(ScriptLocalization.Get("Game_PVP_msg/src_Draw"), IdClForMsg.levelUp, TypeAnimMessage.normalMsg, 2f);
			}
			else
			{
				MessageManager.instance.CreateMessage(ScriptLocalization.Get("Game_PVP_msg/src_YouWinner"), IdClForMsg.levelUp, TypeAnimMessage.normalMsg, 2f);
				base.photonView.RPC("winerNameMessage", PhotonTargets.Others, settings.tekName);
			}
			GameController.instance.addMessageWinnerOnline(settings.tekName);
			if (countWinCash > 0)
			{
				AddReward();
				BCWDebug.Log("Save sendbox round win");
				GameplayEventsManager.instance.SaveCounter(1, settings.keySandboxWins);
			}
		}
		else
		{
			GameTopWindow.instance.IamWinnerActive = false;
			if (GameController.instance.playerScript.IamWinner)
			{
				GameController.instance.playerScript.photonView.RPC("SetWinnerIcon", PhotonTargets.All, false);
			}
		}
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			listPlayer.points = 0;
		}
		gameIsStarted = false;
		timerStart = false;
		GameplayEventsManager.instance.SaveAndReset(true);
	}

	public void AddReward()
	{
		int num = 50;
		settings.CathedExeptions += num;
	}

	[PunRPC]
	public void winerNameMessage(string name)
	{
		MessageManager.instance.CreateMessage(name + ScriptLocalization.Get("Game_PVP_msg/src_PlayerWinnerNoColor"), IdClForMsg.levelUp, TypeAnimMessage.normalMsg, 2f);
	}

	public void EndPVPGame()
	{
		BCWDebug.LogError("ACTIVATE ENDPVPGAME AND THIS FAILS");
		GameController.instance.playerScript.ExplosionAllMine();
		GameController.instance.playerScript.ExplosionAllGrenade();
		PointerController.instance.RemoveAllPointers();
		HitMarks.instance.ResetMark();
		rednessScreen.inst.HideRedness();
		HitMarks.instance.gameObject.SetActive(false);
		rednessScreen.inst.gameObject.SetActive(false);
		MessageWindow.instance.OnExitMapTriggerEventHandler();
		if (FyberWrapper.instance != null)
		{
			FyberWrapper.instance.ShowAds(ADSLocation.PvpMatchEnd);
		}
		int countWinCash = GetCountWinCash();
		settings.SaveCathedExeptionsToStorager();
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (GameController.instance.playerScript.DeathCount == 0)
		{
			GameController.instance.playerScript.DeathCount = 1;
		}
		FlurryWrapper.UpdateKillRate((float)GameController.instance.playerScript.Points / (float)GameController.instance.playerScript.DeathCount);
		GameController.instance.playerScript.DeathCount = 0;
		FlurryWrapper.UpdateAvaregeKill(GameController.instance.playerScript.Points);
		dictionary.Clear();
		string text = ((!string.IsNullOrEmpty(PhotonNetwork.room.customProperties["pass"].ToString())) ? "private" : string.Empty);
		dictionary.Add("Tier " + CupsManager.CurrentTier, "PVP " + text);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_MULTIPLAYER_MODE_RATING, dictionary);
		if (gameIsStarted && countWinCash > 0)
		{
			settings.CathedExeptions += countWinCash;
		}
		ReputationMapInfo reputationMapInfo = default(ReputationMapInfo);
		if (string.IsNullOrEmpty(PhotonNetwork.room.customProperties["pass"].ToString()))
		{
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, int> victinID in GameController.instance.playerScript.victinIDs)
			{
				list.Add(victinID.Value);
			}
			addReputation = (int)reputationMapInfo.curReputation - myRespect;
		}
		myPlayerPlace = GameController.instance.sortListPlayers();
		myRespect = (int)reputationMapInfo.curReputation;
		GameController.instance.playerScript.victinIDs.Clear();
		if (GameController.instance.playerScript != null && (GameController.instance.playerScript.inCar || GameController.instance.playerScript.inHelic))
		{
			GameController.instance.playerScript.isNeedGetOut = true;
			GameController.instance.playerScript.GetOutOfCar(false);
		}
		GameController.instance.playerScript.DisableJetpackParticle();
		GameController.instance.playerScript.tController.jetpack.activated = false;
		GameController.instance.playerScript.SetActiveComponentBesidesControl(false);
		if (PrivateCarManager.instance.currentCar != null)
		{
			BCWDebug.LogError("EndPVPGame");
			PrivateCarManager.instance.currentCar.transform.position = Vector3.up * -1000f;
		}
		gameIsStarted = false;
		timerStart = false;
		endOfRound = true;
		string key = "Achievement_PVP_" + SceneManager.GetActiveScene().name;
		if (!BCWStorage.Get<bool>(key))
		{
			BCWStorage.Set(key, true);
		}
		if (GameController.instance.playerScript != null)
		{
			int points = GameController.instance.playerScript.Points;
			lbKillPVP.text = string.Empty + GameController.instance.playerScript.Points;
			if (BCWStorage.Get<int>(settings.keyMaxCountPVPKills) < points)
			{
				BCWStorage.Set(settings.keyMaxCountPVPKills, points);
			}
		}
		ResetTimer();
		if (countWinCash > 0)
		{
			labelWinCash.text = string.Empty + countWinCash;
			GameplayEventsManager.instance.SaveCounter(1, settings.keyPVPWins);
		}
		GameController.instance.ResetSettingsLevel();
		MarketController.Instance.HideMarket();
		settings.SaveCathedExeptionsToStorager();
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			listPlayer.points = 0;
			listPlayer.CancelInvoke("reset");
			listPlayer.CancelInvoke("resetLocal");
		}
		GameplayEventsManager.instance.SaveAndReset(true);
	}

	public int GetCountWinCash()
	{
		bool flag = string.IsNullOrEmpty(PhotonNetwork.room.customProperties["pass"].ToString());
		int num = 0;
		int points = GameController.instance.playerScript.Points;
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			if (listPlayer.Points > num)
			{
				num = listPlayer.Points;
				isDraw = false;
			}
			if (GameController.instance != null && listPlayer != GameController.instance.playerScript && listPlayer.Points >= points)
			{
				return 0;
			}
		}
		if (points <= 0)
		{
			return 0;
		}
		if (flag)
		{
			return 50;
		}
		return -10;
	}

	public int GetPlaceNumber()
	{
		int points2 = GameController.instance.playerScript.Points;
		if (points2 == 0)
		{
			return GameController.instance.listPlayers.Count;
		}
		List<int> points = new List<int>(GameController.instance.listPlayers.Count);
		GameController.instance.listPlayers.ForEach(delegate(PlayerBehavior p)
		{
			points.Add(p.Points);
		});
		points.Sort((int a, int b) => (a > b) ? 1 : (-1));
		for (int i = 0; i < points.Count; i++)
		{
			if (points2 >= points[i])
			{
				return i + 1;
			}
		}
		return points.Count;
	}

	public void ReadyToTakeInfo()
	{
		StartCoroutine(UpdateOtherPlayers());
		PhotonPlayer photonPlayer = PhotonPlayer.Find(PhotonNetwork.player.ID);
		if (bonuseManager.thisScript != null)
		{
			bonuseManager.thisScript.photonView.RPC("SendInfo", PhotonTargets.MasterClient, photonPlayer);
		}
	}

	[PunRPC]
	public void SendInfo(PhotonPlayer player)
	{
		bonuseManager.thisScript.Send(player);
	}

	private IEnumerator UpdateOtherPlayers()
	{
		if (PhotonNetwork.room == null)
		{
			BCWDebug.Log("Room is null.");
		}
		else if (GameController.instance.listPlayers == null)
		{
			BCWDebug.Log("Players list is null.");
		}
		while (PhotonNetwork.room == null || GameController.instance == null || GameController.instance.listPlayers == null)
		{
			yield return null;
		}
		while (PhotonNetwork.room == null || GameController.instance == null || PhotonNetwork.room.playerCount != GameController.instance.listPlayers.Count)
		{
			yield return null;
		}
		foreach (PlayerBehavior player in GameController.instance.listPlayers)
		{
			if (!(player == GameController.instance.playerScript))
			{
				UpdateOtherCarsWhenConnect(player);
			}
		}
		yield return new WaitForSeconds(1f);
	}

	private void UpdateOtherCarsWhenConnect(PlayerBehavior player)
	{
		ExitGames.Client.Photon.Hashtable customProperties = player.photonView.owner.customProperties;
		bool flag = customProperties.ContainsKey(PlayerPropsKeys.isInCar) && (bool)customProperties[PlayerPropsKeys.isInCar];
		bool flag2 = player.inCar || player.inHelic;
		if ((flag && !flag2) || (!flag && flag2))
		{
			int carId = ((!customProperties.ContainsKey(PlayerPropsKeys.carWeAreInId)) ? (-1) : ((int)customProperties[PlayerPropsKeys.carWeAreInId]));
			if (flag)
			{
				player.GetInCarWithConfirmation(player.viewId, carId);
			}
			else
			{
				player.GetOutOfCar(true);
			}
		}
	}

	public void UpdatePlayer(PlayerBehavior player)
	{
		if (player.photonView.owner == null)
		{
			BCWDebug.Log("LOG: player.photonView.owner is null. wtf? Aborting player update.");
			return;
		}
		ExitGames.Client.Photon.Hashtable customProperties = player.photonView.owner.customProperties;
		string weaponName = (string)customProperties[PlayerPropsKeys.weapon];
		string weaponDefaultName = (string)customProperties[PlayerPropsKeys.defaultWeapon];
		bool hasWeapon = customProperties.ContainsKey(PlayerPropsKeys.hasWeapon) && (bool)customProperties[PlayerPropsKeys.hasWeapon];
		player.weaponManager.SetWeaponFromProps(weaponName, weaponDefaultName, hasWeapon);
		if (firstCall)
		{
			firstCall = false;
			bool flag = customProperties.ContainsKey(PlayerPropsKeys.hasCar) && (bool)customProperties[PlayerPropsKeys.hasCar];
			int key = ((!customProperties.ContainsKey(PlayerPropsKeys.privateCarId)) ? (-1) : ((int)customProperties[PlayerPropsKeys.privateCarId]));
			if (flag)
			{
				Vector3 position = (Vector3)customProperties[PlayerPropsKeys.privateCarPosition];
				Quaternion rotation = (Quaternion)customProperties[PlayerPropsKeys.privateCarRotation];
				string textureName = (string)customProperties[PlayerPropsKeys.carSkin];
				if (GameController.instance.viewIdToCar.ContainsKey(key))
				{
					if (GameController.instance.viewIdToCar[key] is CarBehavior)
					{
						(GameController.instance.viewIdToCar[key] as CarBehavior).SetCarFromProps(position, rotation);
						(GameController.instance.viewIdToCar[key] as CarBehavior).SwitchTexture(textureName, true);
					}
				}
				else
				{
					BCWDebug.LogError("LOG: No key in private cars dictionary. This can produce error.");
				}
			}
		}
		string text = (string)customProperties[PlayerPropsKeys.armor];
		if (text != null)
		{
			player.equipmentManager.EquipFromProps(0, text);
		}
		string text2 = (string)customProperties[PlayerPropsKeys.hat];
		if (text2 != null)
		{
			player.equipmentManager.EquipFromProps(1, text2);
		}
		string text3 = (string)customProperties[PlayerPropsKeys.boots];
		if (text3 != null)
		{
			player.equipmentManager.EquipFromProps(2, text3);
		}
		string text4 = (string)customProperties[PlayerPropsKeys.utils];
		if (text4 != null)
		{
			player.equipmentManager.EquipFromProps(3, text4);
		}
		string text5 = (string)customProperties[PlayerPropsKeys.skin];
		if (text5 != null)
		{
			player.SetSkinFromProps(text5);
		}
	}

	public static ExitGames.Client.Photon.Hashtable WipedHash(ExitGames.Client.Photon.Hashtable playerHash)
	{
		ExitGames.Client.Photon.Hashtable hashtable = new ExitGames.Client.Photon.Hashtable();
		foreach (object key in playerHash.Keys)
		{
			hashtable.Add(key, null);
		}
		return hashtable;
	}

	public IEnumerator WaitForSectorsLoad(Action onSectorsLoaded)
	{
		while (!IOSInternetConnection.isEnable)
		{
			yield return new WaitForSeconds(0.3f);
			if ((!Application.loadedLevelName.Equals("Level1") || ManagerPreloadingSectors.thisScript.sectorsLoaded) && PlayerBehavior.MyPlayer.localTeam != 0)
			{
				break;
			}
		}
		onSectorsLoaded();
		while (!GameController.instance.playerScript.inCar && GameController.instance.curTypeGame == TypeGame.tanks)
		{
			yield return null;
		}
		yield return new WaitForSeconds(1.9f);
		MapWindow.instance.gameObject.SetActive(true);
		yield return new WaitForSeconds(2f);
		GameInfoWindow.instance.TurnLoadAnimation(false);
	}

	public double TimeOfRoundStart()
	{
		if (PhotonNetwork.room != null && PhotonNetwork.room.customProperties.ContainsKey("StartRoundTime"))
		{
			return Convert.ToDouble(PhotonNetwork.room.customProperties["StartRoundTime"]);
		}
		return -1.0;
	}

	private void OnApplicationPause(bool pause)
	{
		Debug.LogError("OnApplicationPause");
		if (pause)
		{
			needToCheckRoundIndexAfterPause = true;
			BCWDebug.Log("Save round on pause", "Pause Round Change");
		}
	}

	public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if (stream.isWriting)
		{
			if (roundIndex > 100)
			{
				roundIndex = 0;
			}
			stream.SendNext(roundIndex);
			return;
		}
		int num = roundIndex;
		roundIndex = (int)stream.ReceiveNext();
		if (num != roundIndex)
		{
			needToChangeRoundIndex = false;
		}
		if (needToCheckRoundIndexAfterPause)
		{
			Debug.LogError(startRoundTimeOnPause);
			double num2 = TimeOfRoundStart();
			if (num2 > 0.0)
			{
				needToCheckRoundIndexAfterPause = false;
			}
			if (!CompareStartRoundTime(startRoundTimeOnPause, num2) && num2 > 0.0 && startRoundTimeOnPause != -1.0)
			{
				BCWDebug.LogError(string.Format(" ***************** паузные дела!!! ********************  время было {0}, а сейчас {1}. Делаем таймаут", startRoundTimeOnPause, TimeOfRoundStart()), "zombie");
				startRoundTimeOnPause = TimeOfRoundStart();
				TimeOut();
			}
		}
		else
		{
			double num3 = TimeOfRoundStart();
			if (num3 != -1.0)
			{
				startRoundTimeOnPause = num3;
			}
		}
	}

	private bool CompareStartRoundTime(double startRoundTime, double actualStartRoundTime)
	{
		return Mathf.Abs((float)(actualStartRoundTime - startRoundTime)) < 60f;
	}
}
